package com.ruoyi.basic.service.impl;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.basic.domain.BasicTrain;
import com.ruoyi.basic.domain.BasicUser;
import com.ruoyi.basic.domain.BasicWork;
import com.ruoyi.basic.mapper.BasicUserMapper;
import com.ruoyi.basic.mapper.BasicWorkMapper;
import com.ruoyi.basic.service.IBasicWorkService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.text.Convert;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 工作经历Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-08-22
 */
@Service
public class BasicWorkServiceImpl extends ServiceImpl<BasicWorkMapper, BasicWork> implements IBasicWorkService
{
    @Autowired
    private BasicUserMapper userMapper;

    /**
     * 查询工作经历
     * 
     * @param workId 工作经历主键
     * @return 工作经历
     */
    @Override
    public BasicWork selectBasicWorkByWorkId(Long workId)
    {
        return baseMapper.selectBasicWorkById(workId);
    }

    /**
     * 查询工作经历
     *
     * @param workIds 工作经历主键
     * @return 工作经历
     */
    @Override
    public List<BasicWork> selectBasicWorkByWorkIds(String workIds)
    {
        LambdaQueryWrapper<BasicWork> queryWrapper = new LambdaQueryWrapper<BasicWork>();
        queryWrapper.in(BasicWork::getWorkId, Convert.toLongArray(workIds));
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 查询工作经历列表
     * 
     * @param basicWork 工作经历
     * @return 工作经历
     */
    @Override
    public List<BasicWork> selectBasicWorkList(BasicWork basicWork)
    {
        return baseMapper.selectBasicWorkList(basicWork);
    }

    /**
     * 新增工作经历
     * 
     * @param basicWork 工作经历
     * @return 结果
     */
    @Override
    public int insertBasicWork(BasicWork basicWork)
    {
        if (basicWork.getIsDefault().equals("Y")){
            baseMapper.update(null, new LambdaUpdateWrapper<BasicWork>().set(BasicWork::getIsDefault, "N")
                    .eq(BasicWork::getUserId, basicWork.getUserId()).eq(BasicWork::getIsDefault, "Y"));
        }
        basicWork.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insert(basicWork);
    }

    /**
     * 修改工作经历
     * 
     * @param basicWork 工作经历
     * @return 结果
     */
    @Override
    public int updateBasicWork(BasicWork basicWork)
    {
        if (basicWork.getIsDefault().equals("Y")){
            baseMapper.update(null, new LambdaUpdateWrapper<BasicWork>().set(BasicWork::getIsDefault, "N")
                    .eq(BasicWork::getUserId, basicWork.getUserId()).eq(BasicWork::getIsDefault, "Y")
                    .ne(BasicWork::getWorkId, basicWork.getWorkId()));
        }
        basicWork.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateById(basicWork);
    }

    /**
     * 批量删除工作经历
     * 
     * @param workIds 需要删除的工作经历主键
     * @return 结果
     */
    @Override
    public int deleteBasicWorkByWorkIds(String workIds)
    {
        return baseMapper.deleteBatchIds(Arrays.asList(Convert.toLongArray(workIds)));
    }

    /**
     * 删除工作经历信息
     * 
     * @param workId 工作经历主键
     * @return 结果
     */
    @Override
    public int deleteBasicWorkByWorkId(Long workId)
    {
        return baseMapper.deleteById(workId);
    }

    /**
     * 导入用户工作经历
     *
     * @param workList 用户工作经历数据列表
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importWork(List<BasicWork> workList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(workList) || workList.size() == 0)
        {
            throw new ServiceException("导入用户工作经历数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        int row = 2;
        String REGEX_LOCALE_ENGLISH = "^[a-zA-Z]{3}\\s[a-zA-Z]{3}\\s\\d{2}\\s\\d{2}:\\d{2}:\\d{2}\\s[A-Z]{3}\\s\\d{4}$";
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BasicWork work : workList)
        {
            try
            {
                //获取用户信息
                BasicUser user = userMapper.selectOne(new LambdaQueryWrapper<BasicUser>()
                        .eq(BasicUser::getIdCard, work.getIdCard()).last("limit 1"));
                if(StringUtils.isNotNull(user)) {
                    work.setUserId(user.getId());
                }else{
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、第 " + row + "行导入失败，员工 " + work.getUserName() + " 不存在");
                    continue;
                }

                SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);

                if(work.getStartTime().matches(REGEX_LOCALE_ENGLISH)) {
                    Date startTime = dateFormat.parse(work.getStartTime());
                    work.setStartTime(DateUtils.parseDateToStr("yyyy-MM-dd", startTime));
                }
                if(work.getEndTime().matches(REGEX_LOCALE_ENGLISH)) {
                    Date endTime = dateFormat.parse(work.getEndTime());
                    work.setEndTime(DateUtils.parseDateToStr("yyyy-MM-dd", endTime));
                }
                if(work.getWorkTime().matches(REGEX_LOCALE_ENGLISH)) {
                    Date workTime = dateFormat.parse(work.getWorkTime());
                    work.setWorkTime(DateUtils.parseDateToStr("yyyy-MM-dd", workTime));
                }

                work.setCreateBy(operName);
                this.insertBasicWork(work);
                successNum++;
                successMsg.append("<br/>" + successNum + "、工作经历 " + work.getWorkPost() + " 导入成功");
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、员工 " + work.getUserName() + " 工作经历导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
            finally {
                row++;
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
